package com.zjl.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，底层逻辑就是AOP
 */

//拦截添加以下注释的Controller
@ControllerAdvice(annotations = {RestController.class, Controller.class})

//由于需要返回json数据,添加该注释
@ResponseBody

@Slf4j
public class GlobalExceptionHandler {
    /**
     * 异常处理方法
     * @param ex
     * @return
     */
    //此异常处理器处理的异常类型为：SQLIntegrityConstraintViolationException.class
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> ExceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());

        //若sql问题出现在 “字段名重复” ,将重复的字段找出并返回
        if (ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg=split[2]+"已存在";
            return R.error(msg);
        }

        return R.error("未知错误");
    }

    /**
     * 业务异常处理方法
     * @param ex
     * @return
     */
    //此异常处理器处理的异常类型为：CustomException.class
    @ExceptionHandler(CustomException.class)
    public R<String> ExceptionHandler(CustomException ex){
        log.error(ex.getMessage());
        return R.error(ex.getMessage());
    }
}
